import { defineStore } from 'pinia'
import type { Question, AnswerResult } from '@/types/question'
import type { Tag, PaginationResponse } from '@/types/index'
import { searchQuestions, getQuestionDetail, getQuestionCategories, submitAnswer } from '@/api/question'

interface QuestionsState {
  questions: Question[]
  question: Question | null
  categories: Tag[]
  pagination: PaginationResponse<Question>
  isLoading: boolean
  error: string | null
  currentAnswer: number | null
  answerResult: AnswerResult | null
  recommendQuestions: Question[]
}

export const useQuestionsStore = defineStore('questions', {
  state: (): QuestionsState => ({
    questions: [],
    question: null,
    categories: [],
    pagination: {
      data: [],
      total: 0,
      page: 1,
      pageSize: 10,
      totalPages: 0
    },
    isLoading: false,
    error: null,
    currentAnswer: null,
    answerResult: null,
    recommendQuestions: []
  }),
  
  getters: {
    // 根据分类获取题目
    questionsByCategory: (state) => (categoryId: string | number) => {
      if (!categoryId) return state.questions
      return state.questions.filter(question => question.category?.id === categoryId)
    },
    
    // 获取当前题目的正确答案
    correctAnswer: (state): number | null => {
      if (!state.question?.answer?.correctOptions) return null
      // 返回第一个正确选项的ID
      return typeof state.question.answer.correctOptions[0] === 'number' 
        ? state.question.answer.correctOptions[0] 
        : null
    }
  },
  
  actions: {
    // 搜索题目
    async fetchQuestions(params?: {
      keyword?: string
      type?: string
      difficulty?: string
      categoryId?: number
      tagIds?: number[]
      page?: number
      pageSize?: number
    }) {
      try {
        this.isLoading = true
        this.error = null
        const response = await searchQuestions(params || {})
        this.questions = Array.isArray(response) ? response : []
        this.pagination.data = this.questions
        this.pagination.total = this.questions.length
        this.pagination.page = 1
        this.pagination.pageSize = 10
        this.pagination.totalPages = Math.ceil(this.pagination.total / this.pagination.pageSize)
        return response
      } catch (error: any) {
        this.error = error.message || '搜索题目失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取题目详情
    async fetchQuestionById(id: number) {
      try {
        this.isLoading = true
        this.error = null
        const question = await getQuestionDetail(id)
        this.question = question
        this.currentAnswer = null
        this.answerResult = null
        return question
      } catch (error: any) {
        this.error = error.message || '获取题目详情失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取题目分类
    async fetchCategories() {
      try {
        this.isLoading = true
        this.error = null
        const categories = await getQuestionCategories()
        this.categories = categories
        return categories
      } catch (error: any) {
        this.error = error.message || '获取分类失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 提交答案
    async submitQuestionAnswer(questionId: number, optionId: number) {
      try {
        this.isLoading = true
        this.error = null
        this.currentAnswer = optionId
        const answerResult = await submitAnswer(questionId, { optionId })
        this.answerResult = answerResult
        return answerResult
      } catch (error: any) {
        this.error = error.message || '提交答案失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 获取推荐题目
    async fetchRecommendQuestions() {
      try {
        this.isLoading = true
        this.error = null
        // 使用搜索题目API作为替代，获取热门题目
        const result = await searchQuestions({ limit: 5, sortBy: 'hot' } as any)
        this.recommendQuestions = Array.isArray(result) ? result.slice(0, 5) : []
        return result
      } catch (error: any) {
        this.error = error.message || '获取推荐题目失败'
        throw error
      } finally {
        this.isLoading = false
      }
    },
    
    // 清除错误
    clearError() {
      this.error = null
    },
    
    // 清除当前题目状态
    clearCurrentQuestion() {
      this.question = null
      this.currentAnswer = null
      this.answerResult = null
    },
    
    // 切换到下一题
    async nextQuestion() {
      if (this.questions.length === 0) return
      
      const currentIndex = this.questions.findIndex(q => q.id === this.question?.id)
      if (currentIndex < this.questions.length - 1) {
        const nextQuestionId = this.questions[currentIndex + 1].id
        await this.fetchQuestionById(typeof nextQuestionId === 'number' ? nextQuestionId : parseInt(nextQuestionId))
      } else {
        // 如果已经是最后一题，可以刷新题目列表或显示提示
        this.error = '已经是最后一题了'
        setTimeout(() => this.clearError(), 2000)
      }
    },
    
    // 切换到上一题
    async prevQuestion() {
      if (this.questions.length === 0) return
      
      const currentIndex = this.questions.findIndex(q => q.id === this.question?.id)
      if (currentIndex > 0) {
        const prevQuestionId = this.questions[currentIndex - 1].id
        await this.fetchQuestionById(typeof prevQuestionId === 'number' ? prevQuestionId : parseInt(prevQuestionId))
      } else {
        this.error = '已经是第一题了'
        setTimeout(() => this.clearError(), 2000)
      }
    }
  }
})